﻿using System;
using System.Net;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;  // This is for password validation
using System.Security.Cryptography;
using Csla.Serialization;
using Csla;
using Csla.Data;


namespace HeThongThongTin.Library.Utility
{
    public class HashFunction
    {
        public static string GeneratePasswordHash(string thisPassword)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] tmpSource;
            byte[] tmpHash;
    
            tmpSource = ASCIIEncoding.ASCII.GetBytes(thisPassword); // Turn password into byte array
            tmpHash = md5.ComputeHash(tmpSource);

            StringBuilder sOuput = new StringBuilder(tmpHash.Length);
            for (int i = 0; i < tmpHash.Length; i++)
            {
                sOuput.Append(tmpHash[i].ToString("X2"));  // X2 formats to hexadecimal
            }
            return sOuput.ToString();
        }

        [Transactional(TransactionalTypes.TransactionScope)]
        public static Boolean VerifyHashPassword(string thisPassword, string thisHash)
        {
            Boolean IsValid = false;
            string tmpHash = GeneratePasswordHash(thisPassword); // Call the routine on user input
            if (tmpHash == thisHash) IsValid = true;  // Compare to previously generated hash
            return IsValid;
        }

        public static string sanitizeInput(string thisInput)
        {
            Regex regX = new Regex(@"([<>""'%;()&])");
            return regX.Replace(thisInput, "");
        }

        public static Boolean isValidPassword(string thisPassword)
        {
            string newPassword = sanitizeInput(thisPassword);
            Regex regX = new Regex(@"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{5,15)");
            return regX.Match(newPassword).Success;
        }


    }
}
